package com.wiegand.loader {
	import com.wiegand.error.ErrorHandler;
	import com.wiegand.event.LoaderEvent;

	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.text.StyleSheet;

	/**
	 * @author kwiegand
	 */
	 
	public class CssLoader extends EventDispatcher{

		private static var _instance : CssLoader;
					
		private var _loader : URLLoader;	
			
		private var _styleSheet : StyleSheet;


		public static function getInstance() : CssLoader{
			
			if( _instance == null )
				_instance = new CssLoader( new SingletonEnforecer() );
			
			return _instance;
			
		}
		
		public function CssLoader( blocker:SingletonEnforecer ):void{
			
			if ( blocker == null ) {
				
            	throw new Error("Error: Instantiation failed: Use CssLoader.getInstance() instead of new.");
          
          	}
          	else{
          	
          		init();
          	
          	}
		
		}
		
		private function init() : void{
			
			_styleSheet = new StyleSheet();
			
			_loader = new URLLoader();
			_loader.dataFormat = URLLoaderDataFormat.TEXT;
			_loader.addEventListener( Event.COMPLETE, handleComplete );
			_loader.addEventListener( ErrorEvent.ERROR, errorHandler);
			_loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			
		}
		
		
		private function errorHandler( e: ErrorEvent) :void{
				
			ErrorHandler.getInstance().show(3);
			
		}
		
		
		public function load( file : String ):void{
		
			dispatchEvent( new LoaderEvent( LoaderEvent.EVENT_START_LOADING ) );				
				
			try{
				_loader.load( new URLRequest( file ) );
			}
			catch ( e : TypeError){
				ErrorHandler.getInstance().show(3);
			}
		
		}
		
		private function handleComplete( event : Event ) : void {
			
			try{
							
				_styleSheet.parseCSS( event.target[ "data" ] );	
								
				dispatchEvent( new LoaderEvent( LoaderEvent.EVENT_LOADING_COMPLETE ));	
								
			}
			catch ( e : TypeError){
				ErrorHandler.getInstance().show(3);
			}
			
		}
		
		public function getStyleSheet() : StyleSheet{
			
			return _styleSheet;
			
		}
		
		public function clear():void{
			
			_styleSheet.clear();
			_styleSheet = null;
			
			_loader = null;
		
		}
	}
}

internal class SingletonEnforecer {}
